package com.wqiuqiu.gulimall.order.web;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.wqiuqiu.gulimall.order.config.AlipayTemplate;
import com.wqiuqiu.gulimall.order.service.OrderService;
import com.wqiuqiu.gulimall.order.vo.PayAsyncVo;
import com.wqiuqiu.gulimall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class AliPayWebController {

    @Autowired
    OrderService orderService;
    @Autowired
    AlipayTemplate alipayTemplate;
    @ResponseBody
    @GetMapping(value = "/payOrder",produces = "text/html")
    public String payOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getOrderPay(orderSn);
        String pay = alipayTemplate.pay(payVo);
        return pay;
    }

    @ResponseBody
    @PostMapping("/aliPayed/message")
    public String ListenerAliPayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {

        HashMap<String, String> map = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String name : parameterMap.keySet()) {
            String[] values = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            map.put(name, valueStr);
        }

        //TODO 付款成功修改订单状态
        String result = "failed";
        boolean signVerified = AlipaySignature.rsaCheckV1(map, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            result = orderService.handlerPayed(vo);
            System.out.println("验签成功");
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            System.out.println("验签失败");
        }

        return result;
    }
    //帐号：mgjjgr1369@sandbox.com

}
